package com.ruoyi.project.module.ordersDetail.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.gargoylesoftware.htmlunit.javascript.host.Console;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ErpEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.UserUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.module.location.service.ILocationService;
import com.ruoyi.project.module.location.service.LocationServiceImpl;
import com.ruoyi.project.module.products.domain.Products;
import com.ruoyi.project.module.products.mapper.ProductsMapper;
import com.ruoyi.project.module.products.service.IProductsService;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.service.IDictDataService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.project.module.ordersDetail.domain.OrdersDetail;
import com.ruoyi.project.module.ordersDetail.service.IOrdersDetailService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

/**
 * 订单详情 信息操作处理
 *
 * @author lcx
 * @date 2018-08-23
 */
@Controller
@RequestMapping("/module/ordersDetail")
public class OrdersDetailController extends BaseController {
    private String prefix = "module/ordersDetail";

    @Autowired
    private IOrdersDetailService ordersDetailService;
    @Autowired
    private IProductsService iProductsService;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private ILocationService locationService;
    @Autowired
    private IDeptService deptService;

    @RequiresPermissions("module:ordersDetail:view")
    @GetMapping()
    public String ordersDetail(ModelMap mmap) {
        mmap.put("depList", deptService.selectDeptAll());
        return prefix + "/ordersDetail";
    }

    /**
     * 查询订单详情列表
     */
    @RequiresPermissions("module:ordersDetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrdersDetail ordersDetail) {
        ordersDetail.setOrderStatus("10702");
        ordersDetail.setIsDel(0);
        startPageChange();
        if("".equals(ordersDetail.getCompanyID())||ordersDetail.getCompanyID()==null){
            ordersDetail.setCompanyID(UserUtils.getDepId());
        }else if("100".equals(ordersDetail.getCompanyID())){
            ordersDetail.setCompanyID("");
        }

         //根据公司id查询订单
        List<OrdersDetail> list = ordersDetailService.selectOrdersDetailList(ordersDetail);

        List<OrdersDetail> sumCountList = ordersDetailService.selectSumCountOrdersDetailList(ordersDetail);
        return getDataTableAsSum(list,sumCountList);
    }

    /**
     * 新增订单详情
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存订单详情
     */
    @RequiresPermissions("module:ordersDetail:add")
    @Log(title = "订单详情", action = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(OrdersDetail ordersDetail) {
        return toAjax(ordersDetailService.insertOrdersDetail(ordersDetail));
    }

    /**
     * 修改订单详情
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        OrdersDetail ordersDetail = ordersDetailService.selectOrdersDetailById(id);
        mmap.put("ordersDetail", ordersDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单详情
     */
    @RequiresPermissions("module:ordersDetail:edit")
    @Log(title = "订单详情", action = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(OrdersDetail ordersDetail) {
        return toAjax(ordersDetailService.updateOrdersDetail(ordersDetail));
    }

    /**
     * 删除订单详情
     */
    @RequiresPermissions("module:ordersDetail:remove")
    @Log(title = "订单详情", action = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ordersDetailService.deleteOrdersDetailByIds(ids));
    }

    /**
     * 上传面单、发货单
     */
    @GetMapping("/uploadModal/{id}")
    public String uploadModal(@PathVariable("id") String id, ModelMap mmap) {
        OrdersDetail ordersDetail = ordersDetailService.selectOrdersDetailById(id);
        String[] skus = new String[]{ordersDetail.getUnitSKUs()};
        Map<String, List<String>> locations = locationService.selectLocationAsMainSKU(skus);
        mmap.put("ordersDetail", ordersDetail);
        mmap.put("locations", locations);
        return prefix + "/uploadModal";
    }

    @Log(title = "面单、发货单上传", action = BusinessType.IMPORT)
    @PostMapping("/FileUploadServlet")
    @ResponseBody
    public AjaxResult uploadIMG(User user, @RequestParam("img_file") MultipartFile file, HttpServletRequest request) {

        try {
            String fileName = file.getOriginalFilename();
            String[] splitResult = fileName.split("\\.");
            String extension = "." + splitResult[splitResult.length - 1];

            BufferedInputStream bis = new BufferedInputStream(file.getInputStream());

            BufferedImage image = ImageIO.read(bis);
            if (image == null) {
                System.out.println("The file" + fileName + "could not be opened , it is not an image");
                return AjaxResult.error(1, "文件不是图片");
            }
            if (!file.isEmpty()) {
                String path = FileUploadUtils.uploadCommon(RuoYiConfig.getProfile(), "order", file);
                final AjaxResult ajaxResult = fileUrl(fileName, path);
                return fileUrl(fileName, path);
            }
            return error();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @RequiresPermissions("module:ordersDetail:edit")
    @Log(title = "更新面单、发货单", action = BusinessType.UPDATE)
    @PostMapping("/updateBill")
    @ResponseBody
    public AjaxResult updateBill(OrdersDetail ordersDetail) {
        if(ordersDetail.getSendBillUrl().indexOf("profile")==-1&&!"".equals(ordersDetail.getSendBillUrl())){
            ordersDetail.setSendBillUrl("/profile/"+ordersDetail.getSendBillUrl());
        }
        if(ordersDetail.getSurfaceBillUrl().indexOf("profile")==-1&&!"".equals(ordersDetail.getSurfaceBillUrl())){
            ordersDetail.setSurfaceBillUrl("/profile/"+ordersDetail.getSurfaceBillUrl());
        }
        String updateBy = ShiroUtils.getLoginName();
        ordersDetail.setUpdateBy(updateBy);
        return toAjax(ordersDetailService.updateOrdersDetail(ordersDetail));
    }


    @RequiresPermissions("module:ordersDetail:reminder")
    @Log(title = "催单", action = BusinessType.UPDATE)
    @PostMapping("/reminder")
    @ResponseBody
    public AjaxResult reminder(OrdersDetail ordersDetail) {
        String updateBy = ShiroUtils.getLoginName();
        ordersDetail.setUpdateBy(updateBy);
        ordersDetail.setIsUrge(1);

        return toAjax(ordersDetailService.updateOrdersDetail(ordersDetail));
    }

    public AjaxResult printBill() {
        return error();
    }

    @RequiresPermissions("module:ordersDetail:sendout")
    @Log(title = "发货", action = BusinessType.UPDATE)
    @PostMapping("/sendOut")
    @ResponseBody
    public List<Integer> sendOut(OrdersDetail ordersDetail) {
        String updateBy = ShiroUtils.getLoginName();

        String id = ordersDetail.getId();
        ordersDetail = ordersDetailService.selectOrdersDetailById(id);
        ordersDetail.setUpdateBy(updateBy);
        //现在的状态改为上一状态
        ordersDetail.setLastStatus(ordersDetail.getOrderStatus());
        //修改后的状态
        ordersDetail.setOrderStatus(ErpEnums.OrderStatus.Shipped_Order.getValue().toString());
        //将发货日期改为当前时间
        ordersDetail.setShippedDate(DateUtils.getTime());

        //--------------------------修改商品库存信息-------------------------
        ArrayList<String> skuList = new ArrayList<String>();//sku集合
        ArrayList<Integer> numList = new ArrayList<>();//发货数量集合
        skuList.add(ordersDetail.getUnitSKUs());
        numList.add(ordersDetail.getOfItems());

        Products product = productsMapper.selectProductsByMainSKU(ordersDetail.getUnitSKUs());//商品信息

        //发货减少库存数量
        List<Integer> SoldQuantity = iProductsService.uploadProductAsMainSkuAndType(skuList, numList, "SoldQuantity");

        if(product!=null){
            if(ordersDetail.getOfItems()>product.getOnhand()){//如果商品发货数量大于库存数量则放入异常单
                ordersDetail.setOrderStatus("10708");
            }
        }
//        if(SoldQuantity>0){
            ordersDetailService.updateOrdersDetail(ordersDetail);//发货
//        }

        return SoldQuantity;
    }



    /**
     *
     * 功能描述: 批量打印/批量发货/批量删除
     *
     * @param:sign
     * @return:
     * @auther: cbx
     * @date: 2018/9/13 0013 上午 10:07
     */
//   @RequiresPermissions("module:ordersDetail:edit")
    @Log(title = "批量操作", action = BusinessType.UPDATE)
    @PostMapping("/batchUpdateByPrint")
    @ResponseBody
    public  List<Integer> batchUpdateById(@RequestParam(value="ids[]") String[] ids,@RequestParam(value = "sign") String sign){
        return ordersDetailService.batchUpdateById(ids, sign);
    }


    /**
     * 功能描述: 扫码发货弹出模态框
     *
     * @param:flag 判断是哪种发货
     * @return:
     * @auther: cbx
     * @date: 2018/10/6 0006 下午 3:54
     */
    @Log(title = "弹出扫码发货窗口", action = BusinessType.OTHER)
    @GetMapping("/toSweepCodeDelivery")
    public String toSweepCodeDelivery(ModelMap mmap,String flag){
        mmap.put("flag", flag);
        return prefix + "/sweepCodeDelivery";
    }


    /**
     *
     * 功能描述:点击扫码发货
     *
     * @param: orderIds 单据的orderid数组
     * @return:
     * @auther: cbx
     * @date: 2018/10/8 0008 上午 10:27
     */
//    @RequiresPermissions("module:ordersDetail:edit")
    @Log(title = "ConfirmOrder扫码发货", action = BusinessType.UPDATE)
    @PostMapping("/confirmSweepCodeDelivery")
    @ResponseBody
    public List<String> SweepCodeDelivery(@RequestParam(value="orderIds[]") String[] orderIds,String sign) {
        sign = "10702";
        return ordersDetailService.updateOrdersDetailBatch(orderIds,sign);
    }



    /**
     *
     * 功能描述:根据订单sku查找货物位置
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/18 0018 下午 3:29
     */
    @PostMapping("/selectLocationAsMainSKU")
    @ResponseBody
    public Map<String, List<String>> selectLocationAsMainSKU(@RequestParam(value="skus[]") String[] skus){
//        Map<String, List<String>> stringListMap = locationService.selectLocationAsMainSKU(new String[]{"HSQ0894HH", "HSQ0005AB"});
        Map<String, List<String>> stringListMap = locationService.selectLocationAsMainSKU(skus);
        return stringListMap;
    }


    /**
     *
     * 功能描述：删除备注弹出模态框
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/15 0015 下午 3:57
     */
    @Log(title = "点击删除弹窗", action = BusinessType.OTHER)
    @GetMapping("/deletePopup")
    public String deletePopup(ModelMap mmap,String id){
        OrdersDetail ordersDetail = ordersDetailService.selectOrdersDetailById(id);
        mmap.put("ordersDetail",ordersDetail);
        return prefix + "/deleteRemark";
    }

    /**
     * 功能描述:添加删除备注
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/15 0015 下午 5:03
     */
//    @RequiresPermissions("module:ordersDetail:deleteRemark")
    @Log(title = "删除订单添加备注", action = BusinessType.UPDATE)
    @PostMapping("/deleteRemark")
    @ResponseBody
    public AjaxResult deleteRemark(OrdersDetail ordersDetail){
        return toAjax(ordersDetailService.updateOrdersDetail(ordersDetail));
    }

    /**
     *
     * 功能描述：删除备注弹出模态框
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/15 0015 下午 3:57
     */
    @Log(title = "点击批量删除弹窗", action = BusinessType.OTHER)
    @GetMapping("/batchDeletePopup")
    public String batchDeletePopup(ModelMap mmap,String[] ids){
        mmap.put("ids",ids);
        return prefix + "/batchDeleteRemark";
    }

    /**
     * 功能描述:添加删除备注
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/15 0015 下午 5:03
     */
//    @RequiresPermissions("module:ordersDetail:deleteRemark")
    @Log(title = "批量删除订单添加备注", action = BusinessType.UPDATE)
    @PostMapping("/batchDeleteRemark")
    @ResponseBody
    public AjaxResult OrdersDetailController(@RequestParam(value="ids[]") String[] ids,@RequestParam(value="bz") String bz){
        return toAjax(ordersDetailService.batchDeleteRemark(ids, bz));
    }


    /**
     * 功能描述:批量打印预览弹窗
     *
     * @param:
     * @return:
     * @auther: cbx
     * @date: 2018/10/23 0023 下午 4:14
     *
     */
    @GetMapping("/toPrintPreview")
    public String toPrintPreview(ModelMap mmap,String[] ids){
        List<OrdersDetail> ordersDetails = ordersDetailService.selectOrderDetailsByIds(Arrays.asList(ids));
        String skus[] = new String[ordersDetails.size()];
        for(int i = 0;i<ordersDetails.size();i++){
            skus[i] =ordersDetails.get(i).getUnitSKUs();
        }
        Map<String, List<String>> stringListMap = locationService.selectLocationAsMainSKU(skus);
        mmap.put("ordersDetails",ordersDetails);
        mmap.put("locations",stringListMap);
        mmap.put("skus",skus);
        return prefix + "/toPrintPreview";
    }


    private String getDictValueByLabel(String label, List<DictData> list) {
        for (DictData dictData : list) {
            if (label.equalsIgnoreCase(dictData.getDictLabel())) {
                return dictData.getDictValue();
            }
        }

        return "";
    }

    private String getDictLabelByValue(String Value, List<DictData> list) {
        for (DictData dictData : list) {
            if (dictData.getDictValue().equalsIgnoreCase(Value)) {
                return dictData.getDictLabel();
            }
        }

        return "";
    }




}
